package org.mwielocha.jxcube.tasks;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class TaskManager {
  
  protected Executor executor;
  
  protected ITask currentTask;
  
  protected Queue<ITask> taskQueue;
  
  public TaskManager() {
    executor = Executors.newFixedThreadPool(1);
    taskQueue = new LinkedList<ITask>();
  }
  
  public void enqueue(final ITask task) {
    
    taskQueue.add(task);
    task.setStatus(TaskStatus.WAITING);
    
    executor.execute(new Runnable() {
      
      @Override
      public void run() {
        currentTask = task;
        task.setStatus(TaskStatus.RUNNING);
        try {
          task.runTask();
         } catch (Exception e) {
          e.printStackTrace();
        } finally {
          task.cleanUp();
          if(task.getStatus() == TaskStatus.RUNNING) {
            task.setStatus(TaskStatus.FINISHED);
          } else if(task.getStatus() == TaskStatus.CANCELING) {
            task.setStatus(TaskStatus.CANCELED);
          }
          taskQueue.remove(task);
          System.out.println("TASK FINISHED");
        }
      }
    }); 
  }
  
  public void executeImmediate(final ITask task) {
    System.out.println("waiting tasks: " + taskQueue.size());
    if(currentTask != null | currentTask.getStatus() != TaskStatus.RUNNING) {
      currentTask.setStatus(TaskStatus.CANCELING);
    }
    
    while(!taskQueue.isEmpty()) {
      ITask t = taskQueue.poll();
      t.setStatus(TaskStatus.CANCELING);
      System.out.println("cancelling task " + t);
    }
    
    enqueue(task);
  }
}
